import {
    reset
} from '@/assets/js/vuex/state'

const mutations = {
    setUser(state, data) {
        state.user = data;
        sessionStorage.setItem("user", JSON.stringify(data));
    },
    setUserHeadImage(state, data) {
        state.user.headImage = data;
        sessionStorage.setItem("user", JSON.stringify(state.user));
    },
    setToken(state, token) {
        state.token = token;
    },
    setResource(state, data) {
        state.res = data;
        sessionStorage.setItem("res", JSON.stringify(data));
    },
    setResPublish(state, data) {
        state.res.isPublish = data;
        sessionStorage.setItem("res", JSON.stringify(state.res));
    },
    setResTitle(state, data) {
        state.res.title = data;
        sessionStorage.setItem("res", JSON.stringify(state.res));
    },
    setImgUrl(state, url) {
        state.res.imgUrl = url;
        sessionStorage.setItem("res", JSON.stringify(state.res));
    },
    addCollectionName(state, name) {
        for (const key in state.collectionNames) {
            const e = state.collectionNames[key];
            if (e.title == name) {
                return;
            }
        }
        state.collectionNames.push({
            "title": name,
            "body": []
        });
        sessionStorage.setItem("collectionNames", JSON.stringify(state.collectionNames));
    },
    setCollectionNames(state, data) {
        data.forEach(e => {
            for (const key in state.collectionNames) {
                const el = state.collectionNames[key];
                if (el.title == e) {
                    return;
                }
            }
            state.collectionNames.push({
                "title": e,
                "body": []
            });
        });
        sessionStorage.setItem("collectionNames", JSON.stringify(state.collectionNames));

    },
    addResToCollection(state, data) {
        state.collectionNames.forEach(e => {
            if (e.title == data.title) {
                e.body.push(data.res);
            }
        })
    },
    setCollectionBody(state, data) {
        for(let i = 0; i < state.collectionNames.length; i++) {
            if (state.collectionNames[i].title == data[i].collectionName) {
                state.collectionNames[i].body = data;
            }
        }
        sessionStorage.setItem("collectionNames", JSON.stringify(state.collectionNames));
    },
    deleteCollectionName(state, name) {
        let index = state.collectionNames.indexOf(name);
        state.collectionNames.splice(index, 1);
    },
    loginOut(state) {
        reset(state);
    }
}

export {
    mutations
}